<template>
  <div class="pos-container">
    <el-row :gutter="20">
      <!-- 左侧商品列表 -->
      <el-col :span="18">
        <el-card class="box-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span>商品列表</span>
              <el-input
                v-model="searchText"
                placeholder="搜索商品"
                class="search-input"
                clearable
                prefix-icon="Search"
              />
            </div>
          </template>
          
          <el-tabs v-model="activeCategory" class="product-tabs">
            <el-tab-pane label="全部" name="all"></el-tab-pane>
            <el-tab-pane v-for="category in categories" :key="category.id" :label="category.name" :name="category.id.toString()"></el-tab-pane>
          </el-tabs>
          
          <div class="product-list">
            <el-card
              v-for="product in displayProducts"
              :key="product.id"
              class="product-card"
              shadow="hover"
              @click="addToCart(product)"
            >
              <div class="product-image">
                <el-image :src="product.imageUrl" fit="cover" lazy />
                <div class="product-add-icon">
                  <i class="el-icon-plus"></i>
                </div>
              </div>
              <div class="product-info">
                <h3 class="product-name">{{ product.name }}</h3>
                <div class="product-price">
                  ¥{{ getProductDisplayPrice(product).toFixed(2) }}
                </div>
              </div>
            </el-card>
          </div>
          
          <div v-if="filteredProducts.length > displayProducts.length" class="load-more">
            <el-button type="primary" plain @click="loadMoreProducts">加载更多</el-button>
          </div>
        </el-card>
      </el-col>
      
      <!-- 右侧购物车 -->
      <el-col :span="6">
        <el-card class="box-card cart-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span>购物车</span>
              <el-button v-if="cart.length > 0" type="text" @click="clearCart">清空</el-button>
            </div>
          </template>
          
          <div v-if="cart.length === 0" class="empty-cart">
            <el-empty description="购物车是空的" />
          </div>
          
          <div v-else class="cart-items">
            <div v-for="(item, index) in cart" :key="item.id + '-' + index" class="cart-item">
              <div class="cart-item-info">
                <div class="cart-item-name">
                  {{ item.name }}
                  <el-tag v-if="item.isGift" size="small" type="success">赠品</el-tag>
                </div>
                <div class="cart-item-price">¥{{ (item.price * item.quantity).toFixed(2) }}</div>
              </div>
              <div class="cart-item-quantity">
                <el-button type="primary" size="small" circle @click="decreaseQuantity(index)">-</el-button>
                <span class="quantity">{{ item.quantity }}</span>
                <el-button type="primary" size="small" circle @click="increaseQuantity(index)">+</el-button>
              </div>
            </div>

            <!-- 新增渠道选择 -->
            <div class="channel-selection">
              <div class="section-title">选择渠道</div>
              <el-radio-group v-model="selectedChannelId" class="channel-radio-group">
                <el-radio 
                  v-for="channel in filteredChannels" 
                  :key="channel.id" 
                  :label="channel.id"
                  border
                  class="channel-radio-item"
                >
                  <div class="channel-radio-content">
                    <img 
                      :src="`/icons/${getChannelIconName(channel.name)}.svg`" 
                      class="channel-icon" 
                      :alt="channel.name"
                    />
                    <span class="channel-name">{{ channel.name }}</span>
                  </div>
                </el-radio>
              </el-radio-group>
            </div>
            
            <!-- 促销功能区域 -->
            <div class="promotion-section">
              <div class="section-title">促销功能</div>
              
              <!-- 折扣设置 -->
              <el-form label-position="left" label-width="80px" class="promotion-form">
                <el-form-item label="折扣">
                  <el-switch v-model="promotions.discount.enabled" />
                </el-form-item>
                
                <template v-if="promotions.discount.enabled">
                  <el-form-item label="折扣类型">
                    <el-radio-group v-model="promotions.discount.type" size="small">
                      <el-radio-button label="none">无折扣</el-radio-button>
                      <el-radio-button label="item">单品折扣</el-radio-button>
                      <el-radio-button label="order">整单折扣</el-radio-button>
                    </el-radio-group>
                  </el-form-item>
                  
                  <el-form-item label="折扣力度" v-if="promotions.discount.type !== 'none'">
                    <el-slider
                      v-model="promotions.discount.value"
                      :min="50"
                      :max="100"
                      :step="5"
                      :format-tooltip="value => `${value / 10}折`"
                      show-stops
                    />
                  </el-form-item>
                  
                  <el-form-item label="商品" v-if="promotions.discount.type === 'item'">
                    <el-select v-model="promotions.discount.itemId" placeholder="选择折扣商品">
                      <el-option
                        v-for="item in cart"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      />
                    </el-select>
                  </el-form-item>
                  
                  <el-form-item label="满额条件" v-if="promotions.discount.type === 'order'">
                    <el-input-number
                      v-model="promotions.discount.minAmount"
                      :min="0"
                      :max="1000"
                      :step="10"
                      :precision="0"
                      size="small"
                    />
                  </el-form-item>
                </template>
              </el-form>
              
              <!-- 买一送一功能 -->
              <el-form label-position="left" label-width="80px" class="promotion-form">
                <el-form-item label="买一送一">
                  <el-switch v-model="promotions.buyOneGetOne.enabled" />
                </el-form-item>
                
                <template v-if="promotions.buyOneGetOne.enabled">
                  <el-form-item label="活动商品">
                    <el-select 
                      v-model="promotions.buyOneGetOne.items" 
                      multiple 
                      placeholder="选择参与活动的商品"
                      style="width: 100%"
                    >
                      <el-option
                        v-for="product in products"
                        :key="product.id"
                        :label="product.name"
                        :value="product.id"
                      />
                    </el-select>
                  </el-form-item>
                </template>
              </el-form>
              
              <!-- 抹零设置 -->
              <el-form label-position="left" label-width="80px" class="promotion-form">
                <el-form-item label="抹零">
                  <el-switch v-model="promotions.roundDown.enabled" />
                </el-form-item>
                
                <template v-if="promotions.roundDown.enabled">
                  <el-form-item label="抹零方式">
                    <el-radio-group v-model="promotions.roundDown.type" size="small">
                      <el-radio-button label="none">不抹零</el-radio-button>
                      <el-radio-button label="yuan">抹去元</el-radio-button>
                      <el-radio-button label="jiao">抹去角</el-radio-button>
                    </el-radio-group>
                  </el-form-item>
                </template>
              </el-form>
            </div>
            
            <div class="cart-footer">
              <div class="cart-total">
                <span class="label">合计:</span>
                <span class="amount">¥{{ finalAmount.toFixed(2) }}</span>
                
                <!-- 显示折扣信息 -->
                <div v-if="hasDiscount" class="discount-info">
                  <div>原价: ¥{{ (totalAmount.value).toFixed(2) }}</div>
                  <div>
                    折扣: {{ getDiscountText() }} 
                    (-¥{{ (totalAmount.value - finalAmount.value).toFixed(2) }})
                  </div>
                </div>
              </div>
              
              <el-button type="primary" size="large" class="checkout-button" @click="checkout">结算</el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 结算对话框 -->
    <el-dialog v-model="checkoutDialogVisible" title="订单结算" width="500px">
      <div class="checkout-dialog">
        <div class="checkout-items">
          <div v-for="(item, index) in cart" :key="index" class="checkout-item">
            <span class="item-name">{{ item.name }}</span>
            <span class="item-quantity">x{{ item.quantity }}</span>
            <span class="item-price">¥{{ (item.price * item.quantity).toFixed(2) }}</span>
          </div>
        </div>
        
        <div class="checkout-total">
          <span class="total-label">订单总额</span>
          <span class="total-amount">¥{{ finalAmount.toFixed(2) }}</span>
        </div>
        
        <el-form :model="checkoutForm" label-width="100px" class="checkout-form">
          <el-form-item label="支付方式">
            <el-radio-group v-model="checkoutForm.paymentMethod">
              <el-radio 
                v-for="method in paymentMethods" 
                :key="method.id" 
                :label="method.id"
              >
                {{ method.name }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          
          <el-form-item label="渠道">
            <el-select v-model="checkoutForm.channelId" placeholder="选择渠道" disabled>
              <el-option
                v-for="channel in channels"
                :key="channel.id"
                :label="channel.name"
                :value="channel.id"
              />
            </el-select>
          </el-form-item>
          
          <el-form-item label="备注">
            <el-input v-model="checkoutForm.note" type="textarea" :rows="2" />
          </el-form-item>
        </el-form>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="checkoutDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmOrder" :loading="confirmLoading">确认支付</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import api from '@/utils/api'
import configService from '@/utils/configService'

// 商品分类
const categories = ref([])

// 商品列表
const products = ref([])

// 渠道列表
const channels = ref([])

// 购物车
const cart = ref([])
const searchText = ref('')
const activeCategory = ref('all')

// 选中的渠道ID
const selectedChannelId = ref(null)

// 促销功能相关状态
const promotions = ref({
  // 折扣功能状态
  discount: {
    enabled: true,              // 是否启用折扣
    type: 'none',               // 折扣类型：none(无折扣), item(单品折扣), order(整单折扣)
    value: 100,                 // 折扣值：100表示无折扣，90表示9折，依此类推
    itemId: null,               // 单品折扣时的商品ID
    minAmount: 0                // 满多少可使用折扣
  },
  // 买一送一功能状态
  buyOneGetOne: {
    enabled: false,             // 是否启用买一送一
    items: []                   // 支持买一送一的商品ID列表
  },
  // 抹零功能状态
  roundDown: {
    enabled: false,             // 是否启用抹零
    type: 'none',               // 抹零类型：none(不抹零), yuan(元), jiao(角)
    value: 0                    // 抹零金额
  }
})

// 结算相关
const checkoutDialogVisible = ref(false)
const confirmLoading = ref(false)
const checkoutForm = ref({
  paymentMethod: 'cash',
  channelId: null,
  note: ''
})

// 支付方式列表
const paymentMethods = ref([])

// 监听selectedChannelId变化，同步到checkoutForm
watch(selectedChannelId, (newVal) => {
  if (newVal) {
    checkoutForm.value.channelId = newVal
    
    // 当渠道变化时，更新购物车中的商品价格
    updateCartPrices(newVal)
    
    // 添加日志，显示当前选中的渠道和价格
    console.log(`已选择渠道: ${newVal}`)
    const selectedChannel = channels.value.find(c => c.id === newVal)
    console.log(`渠道名称: ${selectedChannel?.name}`)
    
    // 打印购物车中的商品价格
    if (cart.value.length > 0) {
      console.log('购物车商品价格:')
      cart.value.forEach(item => {
        const product = products.value.find(p => p.id === item.id)
        if (product) {
          console.log(`${product.name}: 标准价格=${product.price}, 渠道价格=${product.channelPrices?.[newVal] || '未设置'}`)
        }
      })
    }
  }
})

// 更新购物车中的商品价格
const updateCartPrices = (channelId) => {
  if (!channelId || cart.value.length === 0) return
  
  console.log(`开始更新购物车价格，渠道ID: ${channelId}`)
  
  // 遍历购物车中的每个商品
  cart.value.forEach(item => {
    // 查找原始商品数据
    const product = products.value.find(p => p.id === item.id)
    if (product && product.channelPrices && product.channelPrices[channelId]) {
      // 更新为渠道对应的价格
      const oldPrice = item.price
      item.price = product.channelPrices[channelId]
      console.log(`商品 ${item.name} 价格从 ${oldPrice} 更新为 ${item.price}`)
    } else {
      console.log(`商品 ${item.name} 没有渠道价格设置，保持原价 ${item.price}`)
    }
  })
  
  console.log(`已根据渠道 ID:${channelId} 更新购物车价格`)
}

// 获取商品数据
const fetchProducts = async () => {
  try {
    const response = await api.get('/products')
    if (response.data && response.data.status === 'success') {
      products.value = response.data.data
      console.log('成功获取商品数据:', products.value)
      
      // 获取商品对应的渠道价格
      await fetchProductChannelPrices()
    } else {
      console.error('获取商品数据失败:', response.data)
      // 加载硬编码数据作为备份
      loadHardcodedProducts()
    }
  } catch (error) {
    console.error('获取商品数据出错:', error)
    // 加载硬编码数据作为备份
    loadHardcodedProducts()
  }
}

// 获取商品渠道价格
const fetchProductChannelPrices = async () => {
  try {
    // 调用API获取数据
    const response = await api.get('/product-channel-prices')
    if (response.data && response.data.status === 'success') {
      const channelPrices = response.data.data
      
      // 打印原始API返回的价格数据，用于调试
      console.log('API返回的原始渠道价格数据:', channelPrices)
      
      // 检查是否存在重复的价格记录
      const priceMap = {}
      channelPrices.forEach(price => {
        const key = `${price.productId}-${price.channelId}`
        if (priceMap[key]) {
          console.warn(`发现重复的价格记录: 商品ID=${price.productId}, 渠道ID=${price.channelId}, 价格1=${priceMap[key].price}, 价格2=${price.price}`)
        } else {
          priceMap[key] = price
        }
      })
      
      // 使用去重后的价格数据
      const uniquePrices = Object.values(priceMap)
      console.log('去重后的价格数据:', uniquePrices)
      
      applyChannelPrices(uniquePrices)
      console.log('成功从API获取渠道价格数据')
      
      // 打印世涛黑啤的价格信息，用于调试
      const shitao = products.value.find(p => p.name === '世涛黑啤')
      if (shitao) {
        console.log('世涛黑啤价格信息:', {
          id: shitao.id,
          标准价格: shitao.price,
          渠道价格: shitao.channelPrices
        })
      }
      
      // 如果已经选择了渠道，立即更新购物车价格
      if (selectedChannelId.value) {
        updateCartPrices(selectedChannelId.value)
      }
    } else {
      console.error('API返回数据格式错误:', response.data)
      ElMessage.error('获取渠道价格数据失败')
    }
  } catch (error) {
    console.error('获取渠道价格出错:', error)
    ElMessage.error('获取渠道价格失败: ' + (error.response?.data?.message || error.message))
  }
}

// 将渠道价格应用到商品上
const applyChannelPrices = (channelPrices) => {
  console.log('开始应用渠道价格到商品...')
  
  // 为每个商品添加渠道价格数据
  products.value.forEach(product => {
    // 初始化渠道价格对象
    product.channelPrices = product.channelPrices || {}
    
    // 查找该商品的所有渠道价格
    const productPrices = channelPrices.filter(p => p.productId === product.id)
    
    if (productPrices.length > 0) {
      console.log(`商品 ${product.name} (ID=${product.id}) 找到 ${productPrices.length} 个渠道价格记录`)
      
      // 将价格数据整理为映射结构
      productPrices.forEach(priceItem => {
        product.channelPrices[priceItem.channelId] = priceItem.price
        console.log(`设置商品 ${product.name} 在渠道ID=${priceItem.channelId} 的价格为 ${priceItem.price}`)
      })
    } else {
      console.log(`商品 ${product.name} (ID=${product.id}) 没有找到渠道价格记录`)
    }
  })
  
  console.log('渠道价格应用完成')
}

// 生成模拟的渠道价格数据
const generateMockChannelPrices = () => {
  // 创建模拟数据数组
  const mockPrices = []
  
  // 遍历每个商品
  products.value.forEach(product => {
    // 基础价格
    const basePrice = product.price
    
    // 为每个渠道生成价格
    // 抖音渠道ID 1，设置为商品自身价格
    mockPrices.push({ productId: product.id, channelId: 1, price: basePrice })
    
    // 线下渠道ID 2，设置为商品自身价格
    mockPrices.push({ productId: product.id, channelId: 2, price: basePrice })
    
    // 美团和饿了么渠道ID 3和5，价格略高（考虑平台抽成）
    mockPrices.push({ productId: product.id, channelId: 3, price: +(basePrice * 1.1).toFixed(1) })
    mockPrices.push({ productId: product.id, channelId: 5, price: +(basePrice * 1.1).toFixed(1) })
    
    // 京东渠道ID 4，设置为商品自身价格
    mockPrices.push({ productId: product.id, channelId: 4, price: basePrice })
    
    // 小程序渠道ID 6，设置为商品自身价格
    mockPrices.push({ productId: product.id, channelId: 6, price: basePrice })
  })
  
  return mockPrices
}

// 获取分类数据
const fetchCategories = async () => {
  try {
    // 使用配置服务获取分类
    categories.value = await configService.fetchConfig('categories', '/categories')
    console.log('成功获取分类数据:', categories.value)
  } catch (error) {
    console.error('获取分类数据出错:', error)
  }
}

// 获取渠道数据
const fetchChannels = async () => {
  try {
    // 使用配置服务获取渠道
    channels.value = await configService.fetchConfig('channels', '/channels')
    console.log('成功获取渠道数据:', channels.value)
    
    // 如果有渠道数据，默认选择第一个
    if (channels.value.length > 0) {
      selectedChannelId.value = channels.value[0].id
    }
  } catch (error) {
    console.error('获取渠道数据出错:', error)
  }
}

// 获取支付方式数据
const fetchPaymentMethods = async () => {
  try {
    // 使用配置服务获取支付方式
    paymentMethods.value = await configService.fetchConfig('paymentMethods', '/payment-methods')
    console.log('成功获取支付方式数据:', paymentMethods.value)
    
    // 如果有支付方式数据，默认选择第一个
    if (paymentMethods.value.length > 0) {
      checkoutForm.value.paymentMethod = paymentMethods.value[0].id
    }
  } catch (error) {
    console.error('获取支付方式数据出错:', error)
  }
}

// 加载硬编码的备份商品数据
const loadHardcodedProducts = () => {
  // 基础商品数据
  products.value = [
    {
      id: 1,
      name: '青岛啤酒',
      description: '经典口味，畅爽一夏',
      price: 8.0,
      categoryId: 1,
      imageUrl: '/images/products/1.jpg',
      status: true
    },
    {
      id: 2,
      name: '哈啤',
      description: '哈尔滨特产，口感醇厚',
      price: 7.5,
      categoryId: 1,
      imageUrl: '/images/products/2.jpg',
      status: true
    },
    {
      id: 3,
      name: '科罗娜',
      description: '墨西哥风味，配青柠更佳',
      price: 15.0,
      categoryId: 2,
      imageUrl: '/images/products/3.jpg',
      status: true
    },
    {
      id: 4,
      name: '1664白啤',
      description: '法国进口，果香浓郁',
      price: 18.0,
      categoryId: 2,
      imageUrl: '/images/products/4.jpg',
      status: true
    },
    {
      id: 5,
      name: '精酿IPA',
      description: '苦味十足，回味悠长',
      price: 25.0,
      categoryId: 3,
      imageUrl: '/images/products/5.jpg',
      status: true
    },
    {
      id: 6,
      name: '水果啤酒',
      description: '果味浓郁，女士喜爱',
      price: 16.0,
      categoryId: 4,
      imageUrl: '/images/products/6.jpg',
      status: true
    },
    // 添加您之前添加的所有产品
    {
      id: 7,
      name: '比利时小麦',
      description: '异域风味理想宝，曾为远方酿酒师',
      price: 13.0,
      categoryId: 3,
      imageUrl: '/images/products/1.jpg',
      status: true
    },
    {
      id: 8,
      name: '德式小麦',
      description: '传统经典风味，酿酒传承再现',
      price: 11.0,
      categoryId: 3,
      imageUrl: '/images/products/2.jpg',
      status: true
    },
    {
      id: 9,
      name: '绿豆精酿',
      description: '创新口味，清爽宜人',
      price: 15.0,
      categoryId: 3,
      imageUrl: '/images/products/3.jpg',
      status: true
    },
    {
      id: 10,
      name: '浓香荞麦',
      description: '创新口味，清爽宜人',
      price: 15.0,
      categoryId: 3,
      imageUrl: '/images/products/4.jpg',
      status: true
    },
    {
      id: 11,
      name: '世涛黑啤',
      description: '创新口味，清爽宜人',
      price: 15.0,
      categoryId: 3,
      imageUrl: '/images/products/5.jpg',
      status: true
    },
    {
      id: 12,
      name: '双倍IPA',
      description: '创新口味，清爽宜人',
      price: 15.0,
      categoryId: 3,
      imageUrl: '/images/products/6.jpg',
      status: true
    },
    {
      id: 13,
      name: '葡萄芝士',
      description: '创新口味，清爽宜人',
      price: 15.0,
      categoryId: 3,
      imageUrl: '/images/products/7.jpg',
      status: true
    },
    {
      id: 14,
      name: '香甜荔枝',
      description: '创新口味，清爽宜人',
      price: 15.0,
      categoryId: 3,
      imageUrl: '/images/products/8.jpg',
      status: true
    },
    {
      id: 15,
      name: '女神百香果',
      description: '创新口味，清爽宜人',
      price: 15.0,
      categoryId: 3,
      imageUrl: '/images/products/9.jpg',
      status: true
    },
    {
      id: 16,
      name: '龙井小麦',
      description: '创新口味，清爽宜人',
      price: 15.0,
      categoryId: 3,
      imageUrl: '/images/products/10.jpg',
      status: true
    },
    {
      id: 17,
      name: '原浆鲜啤',
      description: '创新口味，清爽宜人',
      price: 15.0,
      categoryId: 3,
      imageUrl: '/images/products/11.jpg',
      status: true
    },
    {
      id: 18,
      name: '西柚茉莉',
      description: '创新口味，清爽宜人',
      price: 15.0,
      categoryId: 3,
      imageUrl: '/images/products/12.jpg',
      status: true
    }
  ]
  
  // 生成渠道价格并应用
  const mockChannelPrices = generateMockChannelPrices()
  applyChannelPrices(mockChannelPrices)
}

// 添加分页加载逻辑
const pageSize = ref(20)
const currentPage = ref(1)

// 计算当前页显示的商品
const displayProducts = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredProducts.value.slice(start, end)
})

// 添加加载更多方法
const loadMoreProducts = () => {
  if (currentPage.value * pageSize.value < filteredProducts.value.length) {
    currentPage.value++
  }
}

// 优化过滤商品的计算属性
const filteredProducts = computed(() => {
  // 使用防抖搜索，减少不必要的计算
  const searchLower = searchText.value.toLowerCase().trim()
  
  // 首先按分类过滤
  let result = activeCategory.value === 'all' 
    ? products.value 
    : products.value.filter(p => p.categoryId === parseInt(activeCategory.value))
    
  // 如果有搜索关键词，再进行搜索过滤
  if (searchLower) {
    result = result.filter(p => 
      p.name.toLowerCase().includes(searchLower) || 
      p.description?.toLowerCase().includes(searchLower)
    )
  }
  
  return result
})

// 添加商品到购物车的函数
const addToCart = (product) => {
  // 防止重复点击
  if (isAddingToCart.value) return
  isAddingToCart.value = true
  
  // 获取当前渠道的价格
  const price = getProductDisplayPrice(product)
  
  // 查找购物车中是否已有此商品
  const existingItem = cart.value.find(item => item.id === product.id && !item.isGift)
  
  if (existingItem) {
    // 已有此商品，增加数量
    existingItem.quantity++
  } else {
    // 添加新商品到购物车
    cart.value.push({
      id: product.id,
      name: product.name,
      price: price,
      originalPrice: product.price,
      quantity: 1,
      isGift: false
    })
  }
  
  // 应用买一送一促销
  applyBuyOneGetOnePromotion()
  
  ElMessage.success(`已添加 ${product.name} 到购物车`)
  
  // 重置标志
  setTimeout(() => {
    isAddingToCart.value = false
  }, 100)
}

// 添加防重复点击标志
const isAddingToCart = ref(false)

// 计算总金额
const totalAmount = computed(() => {
  // 基础金额（不含折扣）
  const baseAmount = cart.value.reduce((sum, item) => sum + item.price * item.quantity, 0)
  
  // 如果折扣功能未启用，直接返回基础金额
  if (!promotions.value.discount.enabled) {
    return baseAmount
  }
  
  // 根据折扣类型计算最终金额
  const discountType = promotions.value.discount.type
  const discountValue = promotions.value.discount.value
  
  // 无折扣
  if (discountType === 'none' || discountValue === 100) {
    return baseAmount
  }
  
  // 单品折扣
  if (discountType === 'item') {
    const itemId = promotions.value.discount.itemId
    if (!itemId) return baseAmount
    
    let discountedAmount = 0
    let regularAmount = 0
    
    cart.value.forEach(item => {
      if (item.id === itemId) {
        // 折扣商品金额
        discountedAmount += item.price * item.quantity * (discountValue / 100)
      } else {
        // 非折扣商品金额
        regularAmount += item.price * item.quantity
      }
    })
    
    return discountedAmount + regularAmount
  }
  
  // 整单折扣
  if (discountType === 'order') {
    const minAmount = promotions.value.discount.minAmount
    
    // 检查是否满足最低消费要求
    if (baseAmount < minAmount && minAmount > 0) {
      return baseAmount
    }
    
    // 应用折扣
    return baseAmount * (discountValue / 100)
  }
  
  return baseAmount
})

// 应用折扣后的最终金额
const finalAmount = computed(() => {
  let amount = totalAmount.value
  
  // 应用抹零
  if (promotions.value.roundDown.enabled && promotions.value.roundDown.type !== 'none') {
    const roundType = promotions.value.roundDown.type
    
    if (roundType === 'yuan') {
      // 抹去元的小数部分
      amount = Math.floor(amount)
    } else if (roundType === 'jiao') {
      // 抹去角的小数部分（保留到角）
      amount = Math.floor(amount * 10) / 10
    }
    
    // 记录抹零金额
    promotions.value.roundDown.value = +(totalAmount.value - amount).toFixed(2)
  } else {
    promotions.value.roundDown.value = 0
  }
  
  return amount
})

// 清空购物车
const clearCart = () => {
  ElMessageBox.confirm('确定要清空购物车吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    cart.value = []
    ElMessage.success('购物车已清空')
  }).catch(() => {})
}

// 结算
const checkout = () => {
  if (cart.value.length === 0) {
    ElMessage.warning('购物车为空，无法结算')
    return
  }
  
  if (!selectedChannelId.value) {
    ElMessage.warning('请先选择渠道')
    return
  }
  
  // 同步渠道ID到结算表单
  checkoutForm.value.channelId = selectedChannelId.value
  
  checkoutDialogVisible.value = true
}

// 确认订单
const confirmOrder = async () => {
  confirmLoading.value = true
  
  try {
    // 构建订单数据
    const orderData = {
      items: cart.value.map(item => ({
        productId: Number(item.id),
        quantity: Number(item.quantity),
        price: Number(item.price)
      })),
      total: Number(finalAmount.value),
      channelId: Number(checkoutForm.value.channelId),
      paymentMethod: checkoutForm.value.paymentMethod,
      note: checkoutForm.value.note
    }
    
    console.log('提交订单数据:', orderData)
    
    // 使用api工具类发送请求
    const response = await api.post('/orders', orderData)
    console.log('订单API响应数据:', response.data)
    
    // 先关闭对话框，避免多个UI元素同时显示
    checkoutDialogVisible.value = false
    
    // 处理成功响应
    if (response.data && response.data.status === 'success') {
      // 清空购物车
      cart.value = []
      
      // 使用MessageBox而不是Message，确保只显示一个消息
      ElMessageBox.alert('订单支付成功!', '成功', {
        confirmButtonText: '确定',
        type: 'success',
        callback: () => {
          // 可选：打印小票
          if (response.data.data && response.data.data.id) {
            printReceipt(response.data.data)
          }
        }
      })
    } else {
      // 服务器返回了响应但状态不是success
      ElMessageBox.alert(response.data?.message || '创建订单失败', '错误', {
        confirmButtonText: '确定',
        type: 'error'
      })
    }
  } catch (error) {
    // 请求异常处理
    console.error('订单创建失败:', error)
    
    // 关闭对话框
    checkoutDialogVisible.value = false
    
    // 避免显示重复错误信息
    if (!error.isAxiosError) {
      ElMessageBox.alert('创建订单失败，请稍后再试', '错误', {
        confirmButtonText: '确定',
        type: 'error'
      })
    }
  } finally {
    confirmLoading.value = false
  }
}

// 获取渠道对应的图标名称
const getChannelIconName = (channelName) => {
  console.log('获取图标名称:', channelName); // 添加日志
  
  const iconMap = {
    '抖音': 'douyin',
    '抖音小店': 'douyin',
    '线下': 'offline',
    '门店自提': 'offline',
    '美团': 'meituan',
    '美团外卖': 'meituan',
    '京东': 'jd',
    '饿了么': 'eleme',
    '小程序': 'miniprogram'
  }
  
  const result = iconMap[channelName] || 'offline';
  console.log('图标名称结果:', result); // 添加日志
  return result;
}

// 在script部分增加计算属性
const filteredChannels = computed(() => {
  // 使用从API获取的渠道数据
  if (channels.value && channels.value.length > 0) {
    return channels.value.filter(channel => channel.status);
  }
  
  // 如果API数据不可用，才使用硬编码数据作为备份
  console.warn('使用硬编码渠道数据作为备份');
  return [
    { id: 1, name: '抖音', status: true },
    { id: 2, name: '线下', status: true },
    { id: 3, name: '美团', status: true },
    { id: 4, name: '京东', status: true },
    { id: 5, name: '饿了么', status: true },
    { id: 6, name: '小程序', status: true }
  ];
});

// 页面加载时获取数据
onMounted(async () => {
  // 清除所有缓存
  localStorage.removeItem('hello_beer_channels');
  localStorage.removeItem('hello_beer_channels_timestamp');
  localStorage.removeItem('hello_beer_products');
  localStorage.removeItem('hello_beer_products_timestamp');
  localStorage.removeItem('hello_beer_categories');
  localStorage.removeItem('hello_beer_categories_timestamp');
  
  console.log('已清除所有本地缓存')
  
  // 初始化配置服务
  await configService.init()
  
  // 从配置服务获取数据
  await fetchCategories()
  await fetchChannels()
  await fetchPaymentMethods()
  
  // 商品数据暂时仍使用API获取
  await fetchProducts()
  
  // 打印当前渠道数据查看问题
  console.log('渠道列表:', channels.value);
  console.log('过滤后的渠道列表:', filteredChannels.value);
  
  // 尝试从localStorage加载促销配置
  try {
    const savedSettings = localStorage.getItem('promotionSettings')
    if (savedSettings) {
      const parsedSettings = JSON.parse(savedSettings)
      
      // 更新促销功能状态
      if (parsedSettings.discount) {
        promotions.value.discount.enabled = parsedSettings.discount.enabled
        promotions.value.discount.type = parsedSettings.discount.defaultType || 'none'
        promotions.value.discount.value = parsedSettings.discount.defaultValue || 100
        promotions.value.discount.minAmount = parsedSettings.discount.minAmount || 0
      }
      
      if (parsedSettings.buyOneGetOne) {
        promotions.value.buyOneGetOne.enabled = parsedSettings.buyOneGetOne.enabled
        promotions.value.buyOneGetOne.items = parsedSettings.buyOneGetOne.items || []
      }
      
      if (parsedSettings.roundDown) {
        promotions.value.roundDown.enabled = parsedSettings.roundDown.enabled
        promotions.value.roundDown.type = parsedSettings.roundDown.defaultType || 'none'
      }
      
      console.log('成功从localStorage加载促销配置')
    }
  } catch (error) {
    console.error('加载促销配置失败:', error)
  }
})

// 获取商品显示价格的函数
const getProductDisplayPrice = (product) => {
  // 获取当前渠道的价格
  let price = product.price
  if (selectedChannelId.value && product.channelPrices && product.channelPrices[selectedChannelId.value]) {
    price = product.channelPrices[selectedChannelId.value]
  }
  return price
}

// 新增方法：获取折扣文本
const getDiscountText = () => {
  const discountType = promotions.value.discount.type
  const discountValue = promotions.value.discount.value
  
  if (discountType === 'none') {
    return '无折扣'
  } else if (discountType === 'item') {
    const itemId = promotions.value.discount.itemId
    if (!itemId) return '无折扣'
    
    const product = products.value.find(p => p.id === itemId)
    if (!product) return '无折扣'
    
    return `${discountValue / 10}折`
  } else if (discountType === 'order') {
    const minAmount = promotions.value.discount.minAmount
    if (minAmount === 0) return '无折扣'
    
    return `${discountValue / 10}折`
  }
  
  return '无折扣'
}

// 新增方法：判断是否有折扣
const hasDiscount = computed(() => {
  const discountType = promotions.value.discount.type
  return discountType !== 'none'
})

// 应用买一送一促销
const applyBuyOneGetOnePromotion = () => {
  // 如果买一送一功能未启用，直接返回
  if (!promotions.value.buyOneGetOne.enabled) return
  
  // 遍历购物车中的每个非赠品商品
  cart.value.forEach(item => {
    // 跳过赠品
    if (item.isGift) return
    
    // 检查商品是否参与买一送一活动
    if (!promotions.value.buyOneGetOne.items.includes(item.id)) return
    
    // 计算应赠送的数量（购买数量的一半，向下取整）
    const giftCount = Math.floor(item.quantity / 2)
    
    // 检查购物车中是否已有该商品的赠品
    const giftItem = cart.value.find(giftItem => giftItem.id === item.id && giftItem.isGift)
    
    if (giftItem) {
      // 如果已有赠品，更新数量
      giftItem.quantity = giftCount
      // 如果赠送数量为0，从购物车中删除
      if (giftCount === 0) {
        const index = cart.value.findIndex(i => i.id === item.id && i.isGift)
        if (index !== -1) {
          cart.value.splice(index, 1)
        }
      }
    } else if (giftCount > 0) {
      // 如果没有赠品且应赠送数量大于0，添加赠品到购物车
      cart.value.push({
        id: item.id,
        name: `${item.name} (赠品)`,
        price: 0, // 赠品价格为0
        quantity: giftCount,
        isGift: true
      })
    }
  })
}

// 增加商品数量
const increaseQuantity = (index) => {
  cart.value[index].quantity += 1
  
  // 如果不是赠品，需要处理买一送一逻辑
  if (!cart.value[index].isGift) {
    applyBuyOneGetOnePromotion()
  }
}

// 减少商品数量
const decreaseQuantity = (index) => {
  if (cart.value[index].quantity > 1) {
    cart.value[index].quantity -= 1
    
    // 如果不是赠品，需要处理买一送一逻辑
    if (!cart.value[index].isGift) {
      applyBuyOneGetOnePromotion()
    }
  } else {
    // 获取要删除的商品信息
    const removedItem = cart.value[index]
    
    // 从购物车删除该商品
    cart.value.splice(index, 1)
    
    // 如果删除的不是赠品，检查是否需要更新赠品
    if (!removedItem.isGift) {
      applyBuyOneGetOnePromotion()
    }
  }
}
</script>

<style scoped>
.pos-container {
  height: 100%;
  background-color: #f8f9fa;
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #ebeef5;
  font-weight: bold;
  font-size: 16px;
}

.search-input {
  width: 250px;
  border-radius: 20px;
}

.product-tabs {
  margin-bottom: 20px;
  border-radius: 4px;
}

.product-tabs :deep(.el-tabs__item) {
  font-size: 14px;
  padding: 0 20px;
  height: 40px;
  line-height: 40px;
}

.product-tabs :deep(.el-tabs__active-bar) {
  background-color: #409EFF;
  height: 3px;
}

/* 调整商品列表布局，使其更加协调 */
.product-list {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-top: 15px;
  padding-bottom: 15px;
  will-change: transform;
}

.product-card {
  cursor: pointer;
  transition: none;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.product-card:hover {
  border-color: #409EFF;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.product-image {
  height: 140px;
  overflow: hidden;
  position: relative;
  background-color: #f5f7fa;
}

.product-image :deep(.el-image) {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.product-info {
  text-align: center;
  padding: 15px 10px;
  background-color: #fff;
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  position: relative;
}

.product-name {
  font-size: 17px;
  margin: 0 0 10px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #333;
  font-weight: 600;
  padding: 5px 10px;
  position: relative;
  text-align: center;
}

.product-name::after {
  content: '';
  display: block;
  width: 40px;
  height: 2px;
  background-color: #409EFF;
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  border-radius: 1px;
}

.product-price {
  color: #f56c6c;
  font-size: 20px;
  font-weight: bold;
  margin-top: 12px;
  background-color: #fff9f9;
  padding: 4px 0;
  border-radius: 16px;
  width: 80%;
  margin-left: auto;
  margin-right: auto;
}

.product-add-icon {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.3);
  display: flex;
  justify-content: center;
  align-items: center;
  opacity: 0;
  color: white;
  font-size: 30px;
}

.product-card:hover .product-add-icon {
  opacity: 1;
}

/* 优化购物车渲染 */
.cart-items {
  max-height: calc(100vh - 350px);
  overflow-y: auto;
  will-change: transform; /* 优化滚动性能 */
}

.cart-card {
  height: calc(100vh - 40px);
  display: flex;
  flex-direction: column;
}

.cart-card :deep(.el-card__body) {
  flex: 1;
  overflow-y: auto;
  padding: 0;
}

.cart-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 10px;
  border-bottom: 1px solid #ebeef5;
}

.cart-item-info {
  flex: 1;
  overflow: hidden;
}

.cart-item-name {
  font-weight: 500;
  margin-bottom: 5px;
  color: #303133;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.cart-item-price {
  font-size: 14px;
  color: #f56c6c;
  font-weight: bold;
}

.cart-item-quantity {
  display: flex;
  align-items: center;
  margin-left: 10px;
}

.quantity {
  width: 30px;
  text-align: center;
  font-weight: bold;
}

/* 渠道选择样式 */
.channel-selection {
  margin-top: 25px;
  padding: 16px;
  border-radius: 8px;
  background-color: #f5f7fa;
  box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.05);
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 16px;
  color: #303133;
  border-left: 4px solid #409EFF;
  padding-left: 10px;
}

.channel-radio-group {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-template-rows: repeat(3, auto);
  gap: 15px;
  width: 100%;
}

.channel-radio-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 100%;
  height: 46px;
  display: flex;
  align-items: center;
  border-radius: 4px;
}

.channel-radio-item :deep(.el-radio__label) {
  padding: 0;
  width: 100%;
}

.channel-radio-item :deep(.el-radio__inner) {
  margin-left: 4px;
  margin-right: 8px;
}

.channel-radio-content {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  height: 100%;
  width: 100%;
  padding-left: 8px;
}

.channel-icon {
  width: 22px;
  height: 22px;
  margin-right: 10px;
  vertical-align: middle;
}

.channel-name {
  font-size: 14px;
  font-weight: 500;
  white-space: nowrap;
}

/* 促销功能样式 */
.promotion-section {
  margin-top: 15px;
  padding: 16px;
  border-radius: 8px;
  background-color: #f5f7fa;
  box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.05);
}

.promotion-form {
  margin-bottom: 15px;
}

.promotion-form :deep(.el-form-item) {
  margin-bottom: 10px;
}

.promotion-form :deep(.el-form-item__label) {
  font-size: 14px;
  font-weight: 500;
}

.promotion-form :deep(.el-switch) {
  margin-right: 10px;
}

.discount-info {
  margin-top: 10px;
  font-size: 12px;
  color: #666;
  line-height: 1.5;
}

.discount-info div:first-child {
  text-decoration: line-through;
}

.cart-footer {
  margin-top: 25px;
  padding: 20px 15px;
  background-color: #f5f7fa;
  border-radius: 8px;
}

.cart-total {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  font-size: 16px;
  padding-bottom: 15px;
  border-bottom: 1px dashed #dcdfe6;
}

.amount {
  color: #f56c6c;
  font-weight: bold;
  font-size: 22px;
}

.checkout-button {
  width: 100%;
  height: 50px;
  font-size: 16px;
  font-weight: bold;
  border-radius: 25px;
  box-shadow: 0 4px 12px rgba(245, 108, 108, 0.3);
  transition: all 0.3s;
}

.checkout-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(245, 108, 108, 0.4);
}

.checkout-dialog {
  padding: 0 20px;
}

.checkout-dialog :deep(.el-dialog__header) {
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
}

.checkout-dialog :deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.checkout-dialog :deep(.el-dialog__body) {
  padding: 30px 20px;
}

.checkout-items {
  max-height: 200px;
  overflow-y: auto;
  margin-bottom: 20px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 8px;
}

.checkout-item {
  display: flex;
  justify-content: space-between;
  padding: 10px;
  border-bottom: 1px dashed #ebeef5;
}

.checkout-item:last-child {
  border-bottom: none;
}

.item-name {
  font-weight: 500;
  color: #303133;
}

.item-quantity {
  color: #606266;
}

.item-price {
  font-weight: bold;
  color: #f56c6c;
}

.checkout-total {
  display: flex;
  justify-content: space-between;
  margin: 25px 0;
  font-size: 16px;
  background-color: #fff9f9;
  padding: 15px;
  border-radius: 8px;
  border: 1px solid #fde2e2;
}

.total-label {
  font-weight: bold;
  color: #303133;
}

.total-amount {
  color: #f56c6c;
  font-weight: bold;
  font-size: 24px;
}

.checkout-form {
  margin-top: 25px;
  border-top: 1px solid #ebeef5;
  padding-top: 25px;
}

.checkout-form :deep(.el-form-item__label) {
  font-weight: 500;
}

.checkout-form :deep(.el-radio) {
  margin-right: 20px;
  margin-bottom: 10px;
}

.checkout-form :deep(.el-select) {
  width: 100%;
}

.checkout-dialog :deep(.el-dialog__footer) {
  padding: 20px;
  border-top: 1px solid #ebeef5;
}

/* 响应式布局调整 */
@media screen and (max-width: 1200px) {
  .product-list {
    grid-template-columns: repeat(3, 1fr);
  }
  
  .channel-radio-group {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media screen and (max-width: 768px) {
  .product-list {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .channel-radio-group {
    grid-template-columns: repeat(1, 1fr);
  }
}

/* 添加加载更多按钮样式 */
.load-more {
  text-align: center;
  margin: 15px 0;
}
</style> 